package com.roncoo.education.course.job;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.roncoo.education.course.service.admin.biz.AdminCourseBiz;
import com.roncoo.education.course.service.admin.biz.AdminExperimentBiz;
import com.roncoo.education.course.service.admin.biz.AdminPostBiz;
import com.roncoo.education.course.service.admin.biz.AdminSphereBiz;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;

import lombok.extern.slf4j.Slf4j;

/**
 * 同步课程数据到es
 *
 * @author fengyw
 */
@Slf4j
@Component
public class CourseJob {

    @Autowired
    private AdminCourseBiz adminCourseBiz;
    
    @Autowired
    private AdminExperimentBiz adminExperimentBiz;
    
    @Autowired
    private AdminSphereBiz adminSphereBiz;
    
    @Autowired
    private AdminPostBiz adminPostBiz;    

    /**
     * 每天凌晨5点执行一次
     */
    @XxlJob("courseJobHandler")
    public void sync() {
    	List<String> succs = new ArrayList<String>();
    	List<String> fails = new ArrayList<String>();
    	try {
    		adminCourseBiz.syncEs();
    		succs.add("课程成功");
    	} catch (Exception e) {
    		e.printStackTrace();
    		fails.add("课程同步失败： " + e.getMessage());
    	}

    	try {
    		adminExperimentBiz.syncEs();
    		succs.add("课程成功");	
    	} catch (Exception e) {
    		e.printStackTrace();
    		fails.add("实验同步失败： " + e.getMessage());
    	}
    	
    	try {
    		adminSphereBiz.syncEs();
    		succs.add("全景成功");
    	} catch (Exception e) {
    		e.printStackTrace();
    		fails.add("全景同步失败： " + e.getMessage());
    	}
    	
    	try {
    		adminPostBiz.syncEs();
    		succs.add("新闻公告成功");
    	} catch (Exception e) {
    		e.printStackTrace();
    		fails.add("新闻公告同步失败： " + e.getMessage());
    	}    	

    	// 全部成功
    	if (fails.size() == 0) {
    		String result = String.join("\r\n", succs.toArray(new String[] {}));    	    		
        	XxlJobHelper.handleSuccess(result);    		
    	}
    	
    	// 个别失败
    	if (fails.size() > 0) {
    		fails.addAll(succs);
    		String result = String.join("\r\n", fails.toArray(new String[] {}));    	    		
        	XxlJobHelper.handleFail(result);
    	}
    }

}
